package com.bookmall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmall.common.constant.DefaultDataConstants;
import com.bookmall.common.constant.MyStatusConstants;
import com.bookmall.member.domain.MemberReceiveAddress;
import com.bookmall.member.mapper.MemberReceiveAddressMapper;
import com.bookmall.member.service.IMemberReceiveAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author 胡菜鸡
 * @Create 2022-04-21-17:36
 */
@Service
public class MemberReceiveAddressServiceImpl extends ServiceImpl<MemberReceiveAddressMapper, MemberReceiveAddress> implements IMemberReceiveAddressService {
    @Autowired
    private MemberReceiveAddressMapper memberReceiveAddressMapper;

    /**
     * 获取会员的所有收获地址列表
     * @author 胡菜鸡
     * @date 2022/4/21 17:46
     */
    @Override
    public List<MemberReceiveAddress> getAddress(String memberId) {
        LambdaQueryWrapper<MemberReceiveAddress> wrapper = new LambdaQueryWrapper<>();
        List<MemberReceiveAddress> addressList = memberReceiveAddressMapper.selectList(wrapper.eq(MemberReceiveAddress::getMemberId, memberId));
        return addressList;
    }

    /**
     * 添加一个新的收货地址
     * @author 胡菜鸡
     * @date 2022/4/24 8:56
     */
    @Override
    @Transactional
    public int insertNewAddress(MemberReceiveAddress memberReceiveAddress) {
        List<MemberReceiveAddress> allAddress = getAddress(memberReceiveAddress.getMemberId());
        //若新的收货地址被设置成了默认地址
        if(allAddress != null && allAddress.size() > 0 && memberReceiveAddress.getDefaultStatus() != null && memberReceiveAddress.getDefaultStatus().equals(MyStatusConstants.DEFAULT)){
            List<MemberReceiveAddress> collect = allAddress.stream().map(memberAddress -> {
                //修改其他地址为非默认地址
                memberAddress.setDefaultStatus(1);
                return memberAddress;
            }).collect(Collectors.toList());
            updateBatchById(collect);
        }
        return memberReceiveAddressMapper.insert(memberReceiveAddress);
    }
}
